﻿using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using Zyg.Utility.DBUtility;
using Zyg.SSO.Core.Business;

namespace Zyg.SSO.Core.Providers.DALProviders
{
    public partial class MySqlProvider : DALProvider
    {
        #region Sql Statements

        private static readonly string SqlInsertRolePermission = "INSERT INTO `RolePermission` (`RoleID`,`PermissionID`) VALUES (@RoleID,@PermissionID); set names utf8;";

        #endregion

        public override void UpdateRolePermission(Zyg.SSO.Core.Business.Role role, List<Zyg.SSO.Core.Business.RolePermission> per)
        {
            MySqlUtility db = new MySqlUtility();
            StringBuilder sql = new StringBuilder();

            sql.Append("delete from `RolePermission` where `RoleID`='" + role.Id + "'");

            for (int i = 0; i < per.Count; i++)
            {
                sql.Append(" insert `RolePermission`(`RoleID`,`PermissionID`) values('" + per[i].RoleID + "','" + per[i].PermissionID + "');");
            }

            sql.Append("set names utf8;");

            try
            {
                db.AutoCloseConnection = false;
                db.Connect();
                db.BeginTransaction();
                db.ExecuteSql(sql.ToString());
                db.CommitTransaction();
            }
            catch
            {
                db.RollbackTransaction();
                db.Disconnect();
            }
        }

        public override void InsertRolePermission(Zyg.SSO.Core.Business.RolePermission roleper)
        {
            MySqlUtility db = new MySqlUtility();

            db.AddParameter("@RoleID", MySqlDbType.VarChar, roleper.RoleID);
            db.AddParameter("@PermissionID", MySqlDbType.VarChar, roleper.PermissionID);

            db.ExecuteSql(SqlInsertRolePermission);
        }

        public override List<Zyg.SSO.Core.Business.Permission> SelectPermissionByRoleID(Guid roleid)
        {
            List<Zyg.SSO.Core.Business.Permission> results = new List<Zyg.SSO.Core.Business.Permission>();

            MySqlUtility db = new MySqlUtility();

            StringBuilder sql = new StringBuilder();

            #region Build SQL

            db.AddParameter("@RoleID", MySqlDbType.VarChar, roleid);

            sql.Append("SELECT `PermissionID` FROM `RolePermission` where `RoleID`=@RoleID; set names utf8;");

            #endregion

            MySqlDataReader reader = db.ExecuteSqlReader(sql.ToString());

            if (reader != null)
            {
                while (reader.Read())
                {
                    Zyg.SSO.Core.Business.Permission per;

                    per = reader.GetGuid(0);

                    results.Add(per);
                }

                reader.Close();
            }

            return results;
        }
    }
}
